<?php

namespace app\api\controller;


use addons\epay\library\Service;
use app\admin\model\Detail;
use app\admin\model\Refund;
use app\admin\model\Ticket;
use app\admin\model\Userticket;
use app\admin\model\Userticketrecord;
use app\common\controller\Api;
use app\admin\model\Order;
use app\admin\model\Orderdetail;
use app\admin\model\Agent;
use app\admin\model\Luck;
use app\admin\model\Otherconfig;
use app\admin\model\Withdraw;
use app\admin\model\Bucket;
use app\admin\model\User;
use app\admin\model\Address;
use app\common\model\ScoreLog;
use think\Db;
use EasyWeChat\Factory;


class Profile extends Api
{
    protected $noNeedLogin = [];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    
    public function getConfig()
    {
        $result = Otherconfig::where(['id' => 1])->field('bucket,peisong,count')->find();
        $this->success('suc',$result);
    }

    public function orderTotal()
    {
        $user = $this->auth->getUserinfo();
        $noPay = Order::where(['user_id' => $this->auth->id,'status' => 0])->count();//待支付
        $noGet =  Order::where(['user_id' => $this->auth->id])->where('status','in','1,2')->count();//收获
        $get = Order::where(['user_id' => $this->auth->id,'status' => 4])->count();//已完成
        $ticketCount = Db::name('user_ticket_record')->where(['user_id' => $this->auth->id,'status' => 1])->count();//水票数量
        
        return $this->success('suc',['no_pay' => $noPay,'noGet' => $noGet,'get' => $get,'ticketNum' => $ticketCount,'score' => $user['score'],'waterNum' => $user['num']]);
    }
    /**
     * 我的订单
     * Summary of order
     * @param mixed $status
     * @param mixed $page
     */
    public function order($status = 0,$page = 1,$active = 0)
    {
       $where['user_id'] = $this->auth->id;
       if($status == 1 || $status == 2) {
         $where['status'] = ['in',[1,2]];
       } else {
        $where['status'] = $status;
       }
        $list = Order::where($where)->order('id desc')->paginate(20,false,['page' => $page])->each(function($item){
            $orderDetail = Orderdetail::where(['order_sn' => $item['order_id']])->select();
            foreach($orderDetail as $key => $value) {
                $orderDetail[$key]['images'] = dealImages($this->request->domain(),$value['images']);
            }
            $item['orderDetail'] =  $orderDetail;
            $item['type'] =  1;
        });
        
        return $this->success('suc',$list);
    }
    public function orderDetail($orderSn = null)
    {
        if(empty($orderSn)) $this->error('fail');

        $orderDetail = Order::where(['order_id' => $orderSn])->find();
        $orderDetail['addressDetail']  = Address::find($orderDetail['address_id']);
        $orderDetail['type'] = 1;
        $detail = Orderdetail::where(['order_sn' => $orderSn])->select();
        foreach($detail as $key => $value) {
            $detail[$key]['images'] = dealImages($this->request->domain(),$value['images']);
        }
        $orderDetail['orderDetail'] =    $detail;
       
        
        return $this->success('suc',$orderDetail);

    }
    public function toAgent()
    {
        $name = $this->request->post('name');
        $phone = $this->request->post('phone');
        $idNum = $this->request->post('idNum');
        $address = $this->request->post('address');
        if(empty( $name) ||  empty( $phone)||  empty( $idNum)|| empty( $address)) $this->error('参数错误');
        if(!preg_match('/^1[3-9]\d{9}$/', $phone)){
            $this->error('手机号码有误');
        }
        $agent = new Agent();
        $checkIdCard = $agent->validateIdCardComplete($idNum);
        if(!$checkIdCard) {
            $this->error('身份证格式错误');
        }
        $agent->name = $name;
        $agent->phone = $phone;
        $agent->id_num = $idNum;
        $agent->address = $address;
        $agent->user_id = $this->auth->id;
        $agent->create_time = time();
        $result = $agent->save();
        if($result) return $this->success('suc');
        $this->error('fail');
    }

    /**
     * 
     * 用户抽奖的产品
     * @return void
     */
    public function list()
    {
        $list = Db::name('luck_list')->where(['status' => 1])->select();
        foreach($list as &$value) {
            $value['name'] = '';
            $value['image'] = '';
            if($value['type'] == 2) {#如果水票
                $detail = Db::name('ticket')->find($value['ticket_id']);
               
                $value['name'] = $detail['title']; 
                $value['image'] = $this->request->domain(). $detail['image'];
            }
            if($value['type'] == 3) {//如果是实物水
                $detail = Db::name('detail')->find($value['detail_id']);
                if($detail) {
                    $value['name'] = $detail['name']; 
               
                    $imageList = explode(',', $detail['images']);
                   
                    $value['image'] = $this->request->domain().$imageList[0];
                }
               
            }
        }
        $this->success('suc',$list);
    }
    //我的抽奖记录
    public function addLuck()
    {
      
        ##抽奖结果
        $otherConfig = Otherconfig::find(1);
        $list = Db::name('luck_list')->where(['status' => 1])->select();
        $randomNumber = mt_rand(1, 100);//随机选中的数
        $currentSum = 0;
        $range = $type =  $status = 0;
        $luckDetail = [];
        foreach($list as  $key => $value ) {
            $currentSum += $value['probability'];
            if ($randomNumber <= $currentSum) {
                $luckDetail = $value;
                break;
            }
        }
       
        $user = $this->auth->getUser();
        if(empty($luckDetail)) {
            $type = 4;
        } else {
            $type = $luckDetail['type'];
        }
      
        Db::startTrans();
        try{
          
            $luckId = 0;
            $num = 1;
            if($type != 4) {
                $luckDetail = Db::name('luck_list')->where('type',$type)->find();
            }
            ##减去积分
            $user->score =  $user->score - $otherConfig['score'];
            $user->save();
            ScoreLog::insert(['createtime' => time(),'user_id' => $this->auth->id,'before' => $user['score'],'score' =>  $otherConfig['score'],'after' =>  $user->score ,'memo' => '抽奖消耗积分','status' => 0,'type' => 3]);
            $detail = '';
            if($type == 0) {#如果中的是积分
                $status = 3;
                $num = $luckDetail['score'];
                ScoreLog::insert(['createtime' => time(),'user_id' => $this->auth->id,'before' => $user->score,'score' =>  $luckDetail['score'],'after' =>  $user->score +  $luckDetail['score'] ,'memo' => '抽奖获得','status' => 0,'type' => 5]);
                $user->score = $user->score + $luckDetail['score'];
            }
            if($type == 1) {#如果中的是水滴
                $status = 3;
                $num = $luckDetail['water_num'];
                ScoreLog::insert(['createtime' => time(),'user_id' => $this->auth->id,'before' => $user->score,'score' =>  $luckDetail['water_num'],'after' =>  $user->num +  $luckDetail['water_num'] ,'memo' => '抽奖获得','status' => 1,'type' => 6]);
                $user->num = $user->num + $luckDetail['water_num'];
            }
            if($type == 2) {#如果中的是水票，记录起来
                //记录到表里
                $status = 3;
                $luckId = $luckDetail['ticket_id'];
               
                $ticketDetail = Db::name('ticket')->find(  $luckId);
                $ticketDetail['image'] = $this->request->domain(). $ticketDetail['image'];
                $detail = $ticketDetail;
                $orderId = Userticket::generateOrderSn();
                $insertIds = Userticket::insertGetId(['user_id' => $this->auth->id,'ticket_id' => $luckId,'num' => 1,'source' => 1,'create_time' => time(),'list' =>$ticketDetail['list'],'order_id' => $orderId ]);
                Db::name('user_ticket_record')->insert(['user_id' => $this->auth->id,'ticket_id' =>  $insertIds,'source' => 1,'list' =>$ticketDetail['list'],'order_id' => $orderId,'create_time' => time(),'origin_id' => $luckId] );
            }
            if($type == 3)  {
                $luckId = $luckDetail['detail_id'];
                $detail = Db::name('detail')->find($luckId);
                $detail['images'] = dealImages($this->request->domain(), $detail['images']);
                $detail['image'] = $detail['images'][0];
            }
            Luck::insert(['user_id' => $this->auth->id,'create_time' => time(),'detail_id' => $luckId,'type' => $type]);
            $user->save();
            Db::commit();
            $this->success('suc',['type' => $type,'num' => $num,'detail' => $detail]);
        } catch(\Exception $e){
            $error = $e->getMessage();
            if(empty($error)) {
                $this->success('suc',['type' => $type,'num' => $num,'detail' => $detail]);
            }
            Db::rollback();
            $this->error($e->getMessage());
        }

       
       
    }
    //我的奖品
    public function luckList()
    {
        $list = Luck::where('type','=',3)->where(['user_id'=>$this->auth->id])->order('id desc')->paginate(20,false,['page'=>1])->each(function(&$item){
            $model =  $item['detail'] = $item['code'] = '';
            $i = 0;
            if($item['type'] == 2) {
                $i = $item['type'];
                $model = new Ticket();
            } 
            if($item['type'] == 3) {
                $i = $item['type'];
                $model = new Detail();
            } 
            if($model) {
                $detail = $model->find($item['detail_id']);
                if($i == 2) {
                    $detail['image'] = $this->request->domain(). $detail['image'];
                }else {//如果是水
                    $tmpDetail = dealImages($this->request->domain(), $detail['images']);
                    $detail['image'] = $tmpDetail[0];
                    $tmpCode = Order::where(['status' => ['in',[1,2,3]],'luck_id' => $item['id']])->find();
                    if($tmpCode) {
                        $item['code'] =  $tmpCode['code'];
                    }
                }
                
                $item['detail'] = $detail;
            }
            
        });
        $this->success('suc',$list );
    } 

    public function comment()
    {
        $orderId = $this->request->post('id',0);
        $start = $this->request->post('start',0);
        $comment = $this->request->post('comment',0);
        if(empty( $orderId )) $this->error('订单信息有误');
        if(empty($start) && empty($comment)) $this->error('评论信息有误');
        $orderDetail = Order::find($orderId);
        if($orderDetail['status'] != 3) $this->error('已完成才能评价');
        $orderDetail->start = $start;
        $orderDetail->comment = $comment;
        $orderDetail->save();
        $this->success('评论成功');
    }
    /**
     * 提现
     * Summary of withdraw
     * @return void
     */
    public function withdraw()
    {
        $user = $this->auth->getUser();
        if(!$user['num']) $this->error('没有水滴');
        $money = $this->request->post('money',0);//提现金额
        $otherConfig = Otherconfig::find(1);
        $change = $user['num'] * $otherConfig['change'];
        if($change < $money) $this->error('余额不足');
        $changeNUm = $money / $otherConfig['change'];//要减去的水滴
        $orderId = Userticket::generateOrderSn('WH');
        $result = Service::withdraw($orderId, $money,$user['open_id']);
        if($result['code'] == 0) {
            $this->error('fail');
        }
        Db::startTrans();
        try{
            #生成提现订单
            Withdraw::insert(['detail' => json_encode( $result ) ,'order_id' => $orderId,'openid' => $user['open_id'], 'user_id' => $this->auth->id,'money' => $money,'source' => 0, 'create_time' => time()]);
            //水滴使用记录
            ScoreLog::insert(['createtime' => time(),'user_id' => $this->auth->id,'before' => $user['num'],'score' =>  $changeNUm,'after' =>  $user['num'] - $changeNUm,'memo' => '水滴提现','status' => 1,'type' => 4]);
            $user->num = $user->num  - $changeNUm;
            $user->save();

            Db::commit();
            $this->success('suc',$result );
        }catch(\Exception $e){
            $error = $e->getMessage();
            if($error) {
                Db::rollback();
                $this->error('fail');
            }
            $this->success('suc',$result);
        }
    }
    /**
     * 
     * 提现确认
     * @param mixed $id
     * @return void
     */
    public function withdrawConfirm($id = '')
    {
        $detail = Withdraw::find($id);
        if(empty($detail)) $this->error('fail');
        if($detail['user_id'] != $this->auth->id) $this->error('fail');
        if($detail['status'] == 0) $this->error('审核中');
        if($detail['status'] == 2) $this->error('提现订单被拒绝');
        $this->success('suc', $detail);
    }
    public function withdrawList($page = 1)
    {
        $list = Withdraw::where(['user_id' => $this->auth->id])->paginate(20,false,['page' => $page]);
        $this->success('suc',$list);
    }
    public function bucket($page = 1)
    {
        $list = Bucket::where(['user_id' => $this->auth->id])->paginate(20,false,['page' => $page])->each(function($item){
            $item['image'] = $this->request->domain().$item['image'];
        });
        
        $this->success('suc',$list);
    }
    public function ticket($orderDetail = '',$type = 0,$status = 0,$page = 1)
    {
        $where['user_id'] = $this->auth->id;
        $where['status'] = $status;//已支付的
        $whereCondition = '';
       
        if($orderDetail) {#如果有值
            $where['source'] = $type;//默认是自购
            $where['status'] = 1;//已支付的
            $orderDetail = json_decode($orderDetail);
            $orderIds = array_column($orderDetail,'detail_id');
            $orderIds = array_unique($orderIds);#所有的id
            //把list里面有这些订单ID的找出来
            $where['list'] = ['in',$orderIds];
         }
    
        $list = Userticketrecord::where($where);
        
        if( $whereCondition) {
            $list->whereRaw($whereCondition);
        }

        $result = $list->paginate(20,false,['page' => $page])->each(function(&$item){
            $detail = Ticket::find($item['origin_id']);
            $item['name'] = $detail['title'];
            $item['image'] = $this->request->domain().  $detail['image'];
            $item['num'] = 1;
            $item['type'] = 0;
            $detail =  Detail::find($item['list']);
              if( $detail) {
                 $detail['images'] = dealImages($this->request->domain(), $detail['images']);
            }
            $item['detail'] =  $detail ;
        });;
        $this->success('suc',$result);
      
    }
    public function ticketDetail($id = null)
    {
        $detail = Userticket::find($id);
        $ticketDetail = Ticket::find($detail['ticket_id']);
        $ticketDetail['image'] = $this->request->domain().  $ticketDetail['image'];
        $detail['ticketDetail'] =  $ticketDetail;
        $detail['type'] =  0;
        $this->success('suc',$detail);
    }
    public function agentArea()
    {
        return $this->success('suc',Db::name('agent_area')->select());
    }
    public function qrcode($type = 'trial',$page = '')
    {
            // 获取用户邀请码
            $inviteCode = $this->auth->getUser()->invite_code;
            if (empty($inviteCode)) {
                $this->error('邀请码不存在');
            }
          
            // 检查缓存，避免重复生成
            $cacheKey = 'qrcode_' . $inviteCode;
            $cachedQrcode = \think\Cache::get($cacheKey);
            if ($cachedQrcode) {
                $this->success('获取成功', [
                    'qrcode' => $cachedQrcode,
                    'invite_code' => $inviteCode
                ]);
            }
            
            // 获取小程序配置
            $siteConfig = Otherconfig::find(1);
            if (empty($siteConfig['app_id']) || empty($siteConfig['secret'])) {
                $this->error('小程序配置不完整');
            }
            
            // 配置EasyWeChat
            $config = [
                'app_id' => $siteConfig['app_id'],
                'secret' => $siteConfig['secret']
            ];
            // 创建小程序实例
            $app = Factory::miniProgram($config);
            // 生成小程序码，将邀请码作为scene参数传递
            // 使用getUnlimit方法生成无限制的小程序码
          
            $response = $app->app_code->getUnlimit($inviteCode, [
                'page' => $page, // 小程序页面路径，根据实际情况调整
                'width' => 430, // 二维码宽度
                'auto_color' => false,
                'line_color' => ['r' => 0, 'g' => 0, 'b' => 0],
                'is_hyaline' => false,
                'env_version' => $type

            ]);
            // 检查响应
            if ($response instanceof \Psr\Http\Message\ResponseInterface) {
                $body = $response->getBody();
                $content = $body->getContents();
                // 检查是否是错误响应
                $data = json_decode($content, true);
                if (isset($data['errcode']) && $data['errcode'] != 0) {
                    $this->error('生成二维码失败：' . ($data['errmsg'] ?? '未知错误'));
                }
                // 将二维码图片转换为base64
                $base64 = base64_encode($content);
                $qrcodeUrl = 'data:image/png;base64,' . $base64;
                
                // 缓存二维码，有效期1小时
                \think\Cache::set($cacheKey, $qrcodeUrl, 3600);
                
                $this->success('生成成功', [
                    'qrcode' => $qrcodeUrl,
                    'invite_code' => $inviteCode
                ]);
            } else {
                $this->error('生成二维码失败');
            }
    }
    public function cancle($id)
    {
        $detail = Order::find($id);
        if($detail['status'] != 0) {
            $this->error('fail');
        }
        if($detail['user_id'] != $this->auth->id) {
            $this->error('fail');
        }
        Order::where(['id'=> $id])->update(['status' => 7]);
        $this->success('suc');
    }
    //退桶
    public function backBucket($id = '')
    {
        $user = $this->auth->getUser();
        $detail = Bucket::find($id);
        if(!$detail) $this->error('fail');
        if($detail['user_id'] != $this->auth->id) $this->error('非法错误');
        if( $detail->status) {
            $this->error('已退，无需重复操作');
        }
        $detail->status = 1;
        $detail->back_time = time();
        $detail->save();//修改退桶时间
        //退款到零钱
        $orderId = Userticket::generateOrderSn('WH');
        //发起提现
        $result = Service::withdraw($orderId, $detail->money,$user['open_id']);
        Withdraw::insert(['desc' =>'退押金桶', 'detail' => json_encode( $result ) ,'order_id' => $orderId,'openid' => $user['open_id'], 'user_id' => $this->auth->id,'money' => $detail->money,'source' => 0, 'create_time' => time()]);
        $this->success('suc');
    }

    public function refund()
    {
        $id = $this->request->post('id','');
        $result = Order::find($id);
        if(empty($result)) $this->error('订单错误');
        if($result->status == 0) $this->error('只有支付后的才能退款');
        if($result->status == 4) $this->error('审核中');
        if($result->status == 5)  $this->error('已同意退款，无需重复操作');
        if($result->status == 6)  $this->error('已拒绝退款，无需重复操作');
        $reason = $this->request->post('reason','');
        Refund::insert(['user_id' =>1,'order_id' => $id,'money' => $result['money'],'create_time' => time(),'reason' => $reason]);
        $result->status = 4;
        $result->save();
        $this->success('suc');
    }

    public function nextUser($page = 1)
    {
        $list = User::where(['pid' => 9])->field('id,username,createtime')->paginate(20,false,['page' => $page])->each(function($item){
            $item['date'] = date('Y-m-d',$item['createtime']);
        });
        $this->success('suc',$list);
    }
    
}
